//
//  DynamicItemBehavior.swift
//  Dynamic
//
//  Created by Yinyin Zeng on 30/5/20.
//  Copyright © 2020 MaoYeYeDeJiangCuCha. All rights reserved.
//

import UIKit

class DynamicItemBehavior: UIView {
    
    let squareViewOne = UIImageView()
    let squareViewTwo = UIImageView()
    var animator = UIDynamicAnimator()
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        
        self.backgroundColor = UIColor(patternImage: UIImage(named: "BackgroundTile")!)
        
        squareViewOne.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        squareViewOne.image = UIImage(named: "Box1")
        self.addSubview(squareViewOne)
        
        squareViewTwo.frame = CGRect(x: 170, y: UIScreen.main.bounds.size.height - 100, width: 80, height: 80)
        squareViewTwo.image = UIImage(named: "Box2")
        self.addSubview(squareViewTwo)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        animator = UIDynamicAnimator(referenceView: self)
        //重力
        let gravityBehavior = UIGravityBehavior(items: [self.squareViewOne])
        //碰撞
        let collisionBehavior = UICollisionBehavior(items: [self.squareViewOne,self.squareViewTwo])
        collisionBehavior.translatesReferenceBoundsIntoBoundary = true
        
        //动力学自身元素
        let dynamicItemBehavior = UIDynamicItemBehavior(items: [self.squareViewTwo])
        //密度
//        dynamicItemBehavior.density = 0.5
        //弹力
        dynamicItemBehavior.elasticity = 1
        //摩擦力
        dynamicItemBehavior.friction = 100
        
        animator.addBehavior(gravityBehavior)
        animator.addBehavior(collisionBehavior)
        animator.addBehavior(dynamicItemBehavior)
    }
    
    /*
     // Only override draw() if you perform custom drawing.
     // An empty implementation adversely affects performance during animation.
     override func draw(_ rect: CGRect) {
     // Drawing code
     }
     */
    
}
